package cn.com.common.job.task;

import java.sql.Timestamp;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.time.format.DateTimeFormatter;
import java.util.Date;
import java.util.List;

import org.quartz.DisallowConcurrentExecution;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;

import cn.com.common.constants.Constants;
import cn.com.gas.entity.GasCamonlinetimeEntity;
import cn.com.gas.entity.GasStationinfoEntity;


import cn.com.gas.service.GasCamonlinetimeService;
import cn.com.gas.service.GasStationinfoService;
import cn.com.thirdparty.entity.ZnGasStation;
import cn.com.thirdparty.mapper.GasDetectionSqlMapper;
import cn.com.thirdparty.mapper.ZnGasStationMapper;
import cn.com.util.TsBqUtils;

@Component("gasZnSynchronizationHistoryData1ProcessTask")
@DisallowConcurrentExecution
public class GasZnSynchronizationHistoryData1ProcessTask {

	// 未使用
	@Value("${gasstation.timedTask.gasZnSynchronizationHistoryData1ProcessTask}")
	private String gasZnSynchronizationHistoryData1ProcessTask;

	private Logger logger = LoggerFactory.getLogger(getClass());

	@Autowired
	private GasStationinfoService stationinfoService;
	@Autowired
	private ZnGasStationMapper znGasStationMapper;
	@Autowired
	private GasDetectionSqlMapper gasDetectionSqlMapper;
	@Autowired
	private GasCamonlinetimeService gasCamonlinetimeService;
	
	public void run(String params) throws Exception {
		logger.debug("gasZnSynchronizationHistoryData1ProcessTask定时任务正在执行，参数为：{}", params);

		logger.debug("application参数为gasZnSynchronizationHistoryData1ProcessTask：{}", gasZnSynchronizationHistoryData1ProcessTask);

		if (gasZnSynchronizationHistoryData1ProcessTask.equals(Constants.JOB_STOP)) {
			logger.debug("application配置文件控制不执行gasZnSynchronizationHistoryData1ProcessTask定时任务");
			throw new Exception("application配置文件控制不执行gasZnSynchronizationHistoryData1ProcessTask定时任务");
		}

		DateTimeFormatter _formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd");
		LocalDate yesterday = LocalDate.now().minusDays(1);
		LocalDateTime startOfYesterday = LocalDateTime.of(yesterday, LocalTime.MIN);
		LocalDateTime endOfYesterday = LocalDateTime.of(yesterday, LocalTime.MAX);

		String time = startOfYesterday.format(_formatter);

		if (TsBqUtils.isNotNull(params)) {

			String[] _paramsArr = params.split("_");

			for (String _params : _paramsArr) {

				DateTimeFormatter formatter1 = DateTimeFormatter.ofPattern("yyyyMMdd");
				LocalDate localDate = LocalDate.parse(_params, formatter1);
				startOfYesterday = LocalDateTime.of(localDate, LocalTime.MIN);
				endOfYesterday = LocalDateTime.of(localDate, LocalTime.MAX);
				time = localDate.format(_formatter);

				logger.debug("gasZnSynchronizationHistoryData1ProcessTask定时任务正在执行，加工日期：{}", _params);
				handleData(startOfYesterday, endOfYesterday, time, _formatter);
				logger.debug("gasZnSynchronizationHistoryData1ProcessTask定时任务正在执行，加工完成：{}", _params);

			}

		} else {

		}
	}

	private void handleData(LocalDateTime startOfYesterday, LocalDateTime endOfYesterday, String time,
			DateTimeFormatter _formatter) throws ParseException {

		LambdaQueryWrapper<GasCamonlinetimeEntity> queryGasCamonlinetime = Wrappers.lambdaQuery();
		queryGasCamonlinetime.ge(GasCamonlinetimeEntity::getMessageDisconnect, startOfYesterday);
		queryGasCamonlinetime.le(GasCamonlinetimeEntity::getMessageDisconnect, endOfYesterday);
		List<GasCamonlinetimeEntity> camonlinetimeList = gasCamonlinetimeService.list(queryGasCamonlinetime);

		if (TsBqUtils.isNotNull(camonlinetimeList)) {

			for (GasCamonlinetimeEntity entity : camonlinetimeList) {
				String camid = entity.getMessageCamid();
				GasStationinfoEntity stationinfo = stationinfoService.getById(camid);
				GasStationinfoEntity stationinfoPid = stationinfoService.getById(stationinfo.getPid());
				ZnGasStation znGasStation = znGasStationMapper.selectById(stationinfoPid.getThirdPartyId());
				
				// 拆分两条
				String messageDisconnect = entity.getMessageDisconnect();
				String messageConnect = entity.getMessageConnect();
				
				// 2024-09-01 00:03:48.440
				
				SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
			        
		        try {
		            Date disconnectDate = sdf.parse(messageDisconnect);
		            Date connectDate = sdf.parse(messageConnect);
		            Timestamp disconnectTimestamp = new Timestamp(disconnectDate.getTime());
		            Timestamp connectTimestamp = new Timestamp(connectDate.getTime());

		            if(znGasStation.getIsNormal() == 1 && znGasStation.getIsValid() == 1){
						String sql1 = "INSERT INTO gas_camera_clog "
								+ "(id, stationId, cameraId, indexCode, status, createTime, errmsg) "
								+ " VALUES ('"+TsBqUtils.getUUID()+"', "+stationinfoPid.getThirdPartyId()+", "+stationinfo.getThirdPartyId()+", 'indexCode', "+0+", '"+disconnectTimestamp+"', '摄像机离线')";
						logger.debug("执行sql1:" + sql1);
						gasDetectionSqlMapper.gasDetectionInsertInto(sql1);
						
						
						String sql2 = "INSERT INTO gas_camera_clog "
								+ "(id, stationId, cameraId, indexCode, status, createTime, errmsg) "
								+ " VALUES ('"+TsBqUtils.getUUID()+"', "+stationinfoPid.getThirdPartyId()+", "+stationinfo.getThirdPartyId()+", 'indexCode', "+1+", '"+connectTimestamp+"', '摄像机恢复在线')";
						logger.debug("执行sql2:" + sql2);
						gasDetectionSqlMapper.gasDetectionInsertInto(sql2);
						
					}
		        } catch (ParseException e) {
		            e.printStackTrace();
		        }
				
			}
		}
	}
}
